昨年までの学びを振り返ってみましょう。
- なぜPythonでなくRを使うのか?
- Reproducible Research (再現可能性)
- Tidy Data (整然データ)
- Data Science Workflow を元に振り返る
- Program
- Import
- Tidy/Transform
- Visualize
- Communicate
2018年12月22日
昨年までの学びを振り返ってみましょう。
Six Reasons To Learn R For Business, R Blogger
乱暴に言うと「Coddの第三正規形」を満たすデータ(対義語はMessy Data)。
日本語では以下で、構造と意味が一致しているデータをTidy Dataと呼びます。
Each data science project is different, but each follows the same general steps.

Data Science Workflow, CC BY 4.0 RStudio
RStudioを利用する場合はR MarkdownのR Notebook機能を活用すると実行結果を確認するためにknitする必要がなく分析が早く分かりやすくなります。
R Notebook機能を上手に活用するには[Ctrl + Enter]と[Ctrl + Shift + Enter]のショートカットキーを利用します。
コードがパイプでつながっている場合は、[Ctrl + Enter]でも一連のコードを実行してくれます。また、ライブラリ読み込みなど共通処理はsetupchunkに記載すると便利です。
\```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
require(DT)
require(dygraphs)
require(plotly)
require(tidyverse) # tidyverseは最後に読み込むとコンフリクトが分かりやすい
\```
R Markdownので最初に任意のchunkを実行した場合、自動的にsetupのチャンクが実行され、初期処理をしてくれる便利な機能。なお、実際に記述する際は先頭の\は記述しないでください。
Rに限らず分析を行う場合にはVSCなどのオープンソース関連の知識も必要になってきています。
データハンドリングは「記録」を分析できるデータにするために必要な前処理。
iris
tidyr::gather関数は、keyに変数名をvalueに値をまとめます。
iris %>% tidyr::gather(key = "key", value = "value", -Species) %>% head()
tidyr::spread関数はkeyを変数名にvalueをその値として展開しますが、行識別のためにユニークな値が必要です。
iris %>% tibble::rowid_to_column("id") %>%
tidyr::gather(key = "key", value = "value", -id, -Species) %>%
tidyr::spread(key = key, value = value) %>% dplyr::select(-id) %>% head()
iris %>% ggplot2::ggplot(ggplot2::aes(x = Species, y = Sepal.Width)) +
ggplot2::geom_boxplot(ggplot2::aes(colour = Species))
iris %>% dplyr::mutate(Species = forcats::fct_reorder(Species, Sepal.Width)) %>%
ggplot2::ggplot(ggplot2::aes(x = Species, y = Sepal.Width)) +
ggplot2::geom_boxplot(ggplot2::aes(colour = Species))
purrr::map関数は指定した引数に対して指定した処理(関数、演算子など)を適用する関数で繰り返し処理に威力を発揮します。並列処理ではありません。例えば、
file_path %>% list.files(path = ., pattern = "(issues_)", full.names = TRUE) %>% purrr::map_df(.x = ., .f = readr::read_csv, locale = readr::locale(encoding = "cp932"))
iris %>% split(.$Species) %>%
purrr::map_df(~ lm(Sepal.Length ~ Sepal.Width, data = .x) %>% broom::tidy(),
.id = "Species")
第6回で説明したpurrr::map_df関数を使った カスタムフィールドの展開 は
with(issues, purrr::map_df(.x = custom_fields, .f = function(.x) {c(.x)}))
以下の処理と等価です(なお、c関数がなくても結果は同じです)。
dplyr::bind_rows( c(list(id = 2L, name = "Resolution", value = "Invalid")), c(list(id = 4L, name = "Affected version")) )
第6回で説明したpurrr::map2_df関数を使った カスタムフィールドの展開 は
with(issues, purrr::map2_df(.x = id, .y = custom_fields,
.f = function(.x, .y) {c(issue_id = .x, .y)}))
以下の処理と等価です。
dplyr::bind_rows( c(issue_id = 16451L, list(id = 2L, name = "Resolution", value = "Invalid")), c(issue_id = 16451L, list(id = 4L, name = "Affected version")) )
iris %>% ggplot2::ggplot(ggplot2::aes(x = Species, fill = Species)) + ggplot2::geom_boxplot(ggplot2::aes(y = Sepal.Length), alpha = 0.5)
iris %>% ggplot2::ggplot(ggplot2::aes(x = Species, fill = Species)) + ggplot2::geom_boxplot(ggplot2::aes(y = Sepal.Length, alpha = 0.5))
iris %>% ggplot2::ggplot(ggplot2::aes(x = Petal.Width, y = Petal.Length)) + ggplot2::geom_point(ggplot2::aes(colour = Species, size = Sepal.Length, shape = Species))
flexdashboradの区切りはMarkdownのHeader記述(#や##)で代用できます。幅は合計が1,000になるようにするといい塩梅です。メニューは#レベルを記述すれば自動的にメニューとなり、タブはカラムやローのレベル(##)で明示的に指定する必要があります。 テンプレート例
# Menu (Tab)
## Coloumn Left {data-width=650}
### Component
## Coloumn Rigth {data-width=350} {.tabset}
### Tab 1
### Tab 2
htmlwidgets はHTMLドキュメントでJavaScriptを用いてインタラクティブな表示を提供するためのベースとなるパッケージです。htmlwidgetsパッケージを利用した様々なパッケージが公開されています。代表的なパッケージには以下のようなものがあります。
| package | description |
|---|---|
| DT | DataTablesライブラリを用いたテーブル(表)表示 |
| plotly | ggplot2オブジェクトを簡単にインタラクティブ化 |
| dygraphs | dygraphsライブライを用いた時系列グラフに特化したパッケージ |
mtcars %>% DT::datatable(options = list(pageLength = 5))
(iris %>% ggplot2::ggplot(ggplot2::aes(x = Petal.Width, y = Petal.Length)) +
ggplot2::geom_point(ggplot2::aes(colour = Species))) %>% plotly::ggplotly()
xts::as.xts(nhtemp) %>% dygraphs::dygraph(main = "New Haven Temperatures") %>% dygraphs::dyRangeSelector()
---
output:
html_document:
df_print: default # データフレーム出力フォーマットはここで指定
---
| value | output |
|---|---|
| default | Rのコンソールでdata.frameを表示した時に使われるテキスト表形式 |
| kable | シンプルな表形式(全て表示されるのでhead関数などで制限要) |
| paged | ページ送りのついたインタラクティブな表形式(htmlwidgetsと相性いまいち) |
| tibble | tibbleクラスを用いた簡易なテキスト表形式 |
身につけるにはアウトプットが大切です。間違っていても構わないのでアウトプットし続ける癖をつけましょう。
2019年度も快適なコミュニケーションスペースである bit & innovation での勉強会を実施できる運びとなりました!
株式会社TISの関係各位に感謝申し上げます。
以上を持ちまして「モダンなRの世界」は終了となります。長い期間ありがとうございました。引き続き関連講義となります。次回(2月)もあるよ!